﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CanSWAT.SWAT
{
    /// <summary>
    /// Input file which just has single parameters
    /// </summary>
    abstract class SingleParameterFile : SWATFile
    {
        private List<SingleParameter> _parameters = null;

        public SingleParameterFile(string file) : base(file)
        {
            //if the parameter file doesn't exist, create with default values
            if (!IsValid) createDefaultFile(File);

            _parameters = new List<SingleParameter>();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(File))
            {
                if(!reader.EndOfStream)
                    _parameters.Add(new SingleParameter(reader.ReadLine()));
            }
        }

        public override bool IsValid
        {
            get
            {
                if (base.IsValid)
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(File))
                    {
                        return reader.ReadToEnd().Length > 0; 
                    }
                }
                return false;
            }
        }

        /// <summary>
        /// A description of this parameter file. Used as the edit window title
        /// </summary>
        public abstract string Description
        {
            get;
        }

        /// <summary>
        /// default file name for this parameter file
        /// </summary>
        public abstract string DefaultFileName
        {
            get;
        }

        /// <summary>
        /// default parameter values
        /// </summary>
        protected abstract List<SingleParameter> DefaultParameters
        {
            get;
        }

        /// <summary>
        /// create the parameter file with default parameter values
        /// </summary>
        /// <param name="file"></param>
        private void createDefaultFile(string file)
        {
            List<SingleParameter> parameters = DefaultParameters;

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(file))
            {
                foreach (SingleParameter p in parameters)
                    writer.WriteLine(p.ToString());
            }
        }
             

        /// <summary>
        /// Save current values into the file in the disk. Existing file will be rewritten.
        /// </summary>
        public void Save()
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(File))
            {
                foreach (SingleParameter p in _parameters)
                    writer.WriteLine(p.ToString());
            }
        }

        public override string ToString()
        {
            return string.Format("{0} - {1}", Description, File);
        }
    }
}
